<template>
  <el-dialog v-model="showDialog" fullscreen destroy-on-close>
    <template #header>
      {{ formData.id === 0 ? "新增文章" : "文章详情" }} -
      {{ formData.heading.length === 0 ? "无标题" : formData.heading }}
    </template>
    <template #default>
      <div class="app-container">
        <div class="table-tools">
          <div>
            <el-button type="primary" @click="drawer = true">
              编辑文章信息
            </el-button>
          </div>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
        <div style="border: 1px solid #ccc">
          <Toolbar
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          />
          <Editor
            style="height: 600px; overflow-y: hidden"
            v-model="formData.content"
            :defaultConfig="editorConfig"
            :mode="mode"
            @on-created="handleCreated"
          />
        </div>
        <el-drawer v-model="drawer">
          <el-form
            label-width="100px"
            :model="formData"
            :rules="rules"
            ref="formRef"
          >
            <el-form-item label="文章ID" prop="id">
              <el-input
                v-model="formData.id"
                placeholder="由系统自动添加"
                disabled
              />
            </el-form-item>
            <el-form-item label="文章封面" prop="cover">
              <articleCover
                v-model="formData.cover"
                width="100%"
                height="180px"
                upload
              />
            </el-form-item>
            <el-form-item label="文章标题" prop="heading">
              <el-input v-model="formData.heading" />
            </el-form-item>
            <el-form-item label="文章作者" prop="author">
              <el-input v-model="formData.author" />
            </el-form-item>
            <el-form-item label="文章类别" prop="categoryId">
              <el-select
                v-model="formData.categoryId"
                placeholder="Select"
                size="large"
                style="width: 240px"
              >
                <el-option
                  v-for="item in category"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="文章上传时间" prop="uploadTime">
              <el-input
                v-model="formData.uploadTime"
                placeholder="由系统自动添加"
                disabled
              />
            </el-form-item>
            <el-form-item label="文章修改时间" prop="lastModifyTime">
              <el-input
                v-model="formData.lastModifyTime"
                placeholder="由系统自动添加"
                disabled
              />
            </el-form-item>
          </el-form>
          <div class="tips">
            <el-text type="primary">
              提示：表单填写完后关闭右弹框单后点击保存即可
            </el-text>
          </div>
          <div style="display: flex; justify-content: center">
            <el-button @click="resetData">还原文章数据</el-button>
          </div>
        </el-drawer>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import articleCover from "@/components/articleCover/index.vue";
import { type CategoryResult } from "@/api/category";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import articleAPI, { type ArticleResult } from "@/api/article";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { FormInstance, FormRules } from "element-plus";

defineOptions({
  name: "ArticleDetail",
});

defineProps({
  category: {
    type: Array as PropType<CategoryResult[]>,
  },
});

const emit = defineEmits(["on-save"]);

const formRef = ref<FormInstance>();
const defaultData: ArticleResult = {
  id: 0,
  cover: "",
  heading: "",
  content: "",
  articlePicture: 0,
  articleVedio: 0,
  categoryId: 1,
  readTime: 0,
  author: "",
  uploadTime: "",
  lastModifyTime: "",
};
const rules = ref<FormRules<ArticleResult>>({
  cover: [
    {
      required: true,
      message: "封面必填",
    },
  ],
  heading: [
    {
      required: true,
      message: "标题必填",
    },
    {
      min: 3,
      max: 50,
      message: "标题为3-50个字符",
    },
  ],
  content: [
    {
      required: true,
      message: "内容必填",
    },
    {
      min: 20,
      message: "内容最少为20字符",
    },
  ],
  author: [
    {
      required: true,
      message: "作者必填",
    },
    {
      min: 2,
      max: 50,
      message: "作者为3-50个字符",
    },
  ],
});

const drawer = ref(false);
const showDialog = ref(false);
const formData = ref<ArticleResult>(defaultData);

const closeClick = () => {
  showDialog.value = !showDialog.value;
};

const save = async () => {
  const validate = formRef.value?.validate(async (valid, fields) => {
    if (valid && formData.value.content.length > 20) {
      if (formData.value.id === 0) {
        await articleAPI.addArticle(formData.value);
        ElMessage.success("新增文章成功");
      } else {
        await articleAPI.editArticle(formData.value);
        ElMessage.success("编辑文章成功");
      }
      emit("on-save");
    } else {
      ElMessage.info("文章内容填写有误，请检查");
    }
  });
  if (!validate && formData.value.id !== 0) {
    await articleAPI.editArticle(formData.value);
    ElMessage.success("编辑文章成功");
  } else if (!validate) {
    ElMessage.info("请填写文章信息");
  }
};

let tmp: ArticleResult = defaultData;

const resetData = () => {
  ElMessage.success("还原文章数据成功");
  formData.value = Object.assign({}, tmp);
};

const propFromData = (data?: ArticleResult) => {
  tmp = Object.assign({}, defaultData, data);
  formData.value = Object.assign({}, defaultData, data);
};

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

const mode = "default";
const toolbarConfig = {};
const editorConfig = { placeholder: "请输入内容..." };

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

watch(showDialog, async (value) => {
  await nextTick();
  if (value) {
    editorRef.value.focus();
  }
});

const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

defineExpose({
  closeClick,
  propFromData,
});
</script>

<style lang="scss" scoped>
.table-tools {
  padding: 10px 0;
}

.el-dropdown {
  margin: 0 10px;
}

.tips {
  margin: 15px;
  margin-left: 80px;
}
</style>
<style>
.el-dialog__header {
  border-bottom: 1px solid rgb(0 0 0 / 10%);
}
</style>
